<?php
/**
 * 修改历史
 * 修改时间：2018/4/10
 * 修改人：lizenan
 * 修改功能：【后台需求】热卖商品改版限时抢GO商品，调整后台热卖商品功能
 * 任务ID：573
 */

namespace backend\controllers;

use Yii;
use yii\web\AdminController;
use backend\models\UploadForm;
use backend\models\HotSaleConfig;
use backend\models\BannerConfig;
use backend\models\GoodsSale;
use PHPExcel;
use backend\models\GoodsSaleEdit;
use common\helps\tools;

class GoodsHotSaleController extends AdminController
{
    public $layout = false;
    //业务关键字
    public $service = 'GoodsHotSale';
    
    public $type = 1;
    
    public function actionIndex()
    {
        $model = new UploadForm();
        $sale_edit = GoodsSale::find()->select('sku')->where('use_flg=1')->limit(10)->asArray()->all();
        return $this->render('index',['model'=>$model,'sale_edit'=>$sale_edit]);
    }
    //查询所有热销组
    public function actionGetHotSale()
    {
        $data = Yii::$app->request->post();
        $type = $this->type;
        $query = HotSaleConfig::find()->select('id,hot_sale_name,sort,memo,platform,use_flg')->where('type='.$type);
        $count = $query->count();
        $sort_string = empty($data['columns'][$data['order'][0]['column']]['data']) ? 'id' : $data['columns'][$data['order'][0]['column']]['data'];
        $list = $query->offset($data['start'])->limit($data['length'])->orderBy(
            [$sort_string=>$data['order'][0]['dir'] == 'asc' ? SORT_ASC : SORT_DESC])->asArray()->all();
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        return \yii\helpers\Json::encode($result);
    }
    //热销组启用禁用
    public function actionChangeHotSaleStatus()
    {
        $data_now = array();
        $model = new HotSaleConfig();
        $data = Yii::$app->request->post();
        $data_now['use_flg'] = $data['use_flg'];
        $data_now['editor'] = $model->getCreator();
        $data_now['edit_time'] = date('Y-m-d H:i:s',time());
        $hot_sale_where = ['id'=>$data['id']];
        $ret = $model::updateAll($data_now,$hot_sale_where);
        if(!$ret){
            throw new \Exception('操作失败');
        }
        $this->retJson('操作成功',200);
    }
    //查询热销组信息及详情数据
    public function actionGetHotSaleDetail()
    {
        $data = Yii::$app->request->post();
        $where = ['group_id'=>$data['id']];
		//add by lizenan 20180410 修改功能：【后台需求】热卖商品改版限时抢GO商品，调整后台热卖商品功能 573 start
        $platform = $data['platform'];
        $result = BannerConfig::find()->select('id,picture_name,product_url,sort,picture_url,picture_alt,sku,category_id,type')->where($where)->orderBy('sort asc')->asArray()->all();
        $val = [];
        if ($platform == '2'){
            if (is_array($result) && count($result) > 0){
                $sku_list = array_column($result, 'sku');
                $sku_name = GoodsSaleEdit::find()->select('sku,goods_name_cn')->where(['sku'=>$sku_list])->asArray()->all();
                $sku_name = count($sku_name) > 0 ? array_combine(array_column($sku_name, 'sku'), $sku_name) : [];
                foreach ($result as $res){
                    if ($res['sku']){
                        $res['goods_name_cn'] = tools::arrayHasValue($sku_name,$res['sku']) ? $sku_name[$res['sku']]['goods_name_cn'] : '';
                        if($res['type'] == '1'){
                            $val['sku'][] = $res;
                        }else{
                            $val['sku_go'][] = $res;
                        }
                    }else{
                        $val['category'][] = $res;
                    }
                }
            }
        }else{
            $val = $result;
        }
        $this->retJson($val,200);
		//add by lizenan 20180410 修改功能：【后台需求】热卖商品改版限时抢GO商品，调整后台热卖商品功能 573 end
    }
    //热销组详情修改
    public function actionChangeHotSale()
    {
        $hot_sale = new HotSaleConfig();
        $data = Yii::$app->request->post();
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $hot_sale_name = $data['hot_sale_name'];
            $platform = $data['platform'];
            $sort = intval($data['sort']);
            $hot_sale_id = $data['hot_sale_id'];
            $use_flg = $data['use_flg'];
            $memo = $data['memo'];
            $type = $this->type;
            if (!$hot_sale_name) {
                throw new \Exception('请输入热销组名称');
            }
            if (!$sort || $sort < 0) {
                throw new \Exception('排序编号不可为空或小于零');
            }
			//add by lizenan 20180410 修改功能：【后台需求】热卖商品改版限时抢GO商品，调整后台热卖商品功能 573 start
            $where_banner = $banner_ids = $banner_ids_sku = $banner_ids_category = $banner_ids_go = array();
            $creator = $hot_sale->getCreator();
            $oper_time = date('Y-m-d H:i:s',time());
            $old_platform = '';
            if ($hot_sale_id){
                $where_banner['group_id'] = $hot_sale_id;
                $hot_sale = HotSaleConfig::findOne($hot_sale_id);
                $old_platform = $hot_sale->platform;
                $bannerAll = BannerConfig::find()->where($where_banner)->asArray()->all();
                if ($hot_sale_id == '1'){
                    $banner_ids = array_column($bannerAll, 'id');
                }else{
                    if (is_array($bannerAll) && count($bannerAll) > 0)foreach ($bannerAll as $banner){
                        if ($banner['sku']){
                            if ($banner['type'] == '1'){
                                $banner_ids_sku[] = $banner['id'];
                            }else{
                                $banner_ids_go[] = $banner['id'];
                            }
                        }else{
                            $banner_ids_category[] = $banner['id'];
                        }
                    }
                }
                $hot_sale->editor = $creator;
                $hot_sale->edit_time = $oper_time;
            }else{
                $has_name = HotSaleConfig::find()->where('hot_sale_name=:hot_sale_name',[':hot_sale_name'=>$hot_sale_name])->asArray()->one();
                if ($has_name['id'] && $has_name['id'] != $hot_sale_id){
                    throw new \Exception('热销组名称重复');
                }
                $hot_sale->creator = $creator;
                $hot_sale->create_time = $oper_time;
                $hot_sale->type = $type;
            }
            $hot_sale->platform = $platform;
            $hot_sale->hot_sale_name = $hot_sale_name;
            $hot_sale->memo = $memo;
            $hot_sale->sort = $sort;
            $hot_sale->use_flg = $use_flg;
            $hot_sale->save();
            $hot_sale_id = $hot_sale->attributes['id'];
            if (!$hot_sale_id){
                throw new \Exception('操作失败，请重试');
            }
            if ($platform == '1'){
                if($old_platform && $old_platform != $platform){
                    $bannerDel = BannerConfig::deleteAll(['group_id'=>$hot_sale_id]);
                    if(!$bannerDel){
                        throw new \Exception('操作失败');
                    }
                }
                $picture_name = $data['picture_name'];
                $banner_config_id = $data['banner_config_id'];
                $sku = $data['sku'];
                $picture_url = $data['picture_url'];
                $picture_alt = $data['picture_alt'];
                $sort = 1;
                if (count($banner_config_id) > 0)for ($i=0;$i<count($banner_config_id);$i++){
                    if ($sku[$i] == '' || $picture_url[$i] == '') continue;
                    $banner = new BannerConfig();
                    if ($banner_config_id[$i]){
                        $banner = $banner->findOne($banner_config_id[$i]);
                        $banner->editor = $creator;
                        $banner->edit_time = $oper_time;
                    }else{
                        $banner->creator = $creator;
                        $banner->create_time = $oper_time;
                    }
                    $banner->group_id = $hot_sale_id;
                    $banner->group_name = $hot_sale_name;
                    $banner->picture_name = $picture_name[$i];
                    $banner->sku = $sku[$i];
                    $banner->sort = $sort;
                    $banner->picture_url = $picture_url[$i];
                    $banner->picture_alt = $picture_alt[$i];
                    $banner->save();
                    $banner_id = $banner->attributes['id'];
                    if (!$banner_id){
                        throw new \Exception('热销商品明细操作失败');
                    }
                    $sort++;
                }
                if (is_array($banner_ids) && count($banner_ids))foreach ($banner_ids as $bannerId){
                    if (!in_array($bannerId,$banner_config_id)){
                        $bannerDel = BannerConfig::deleteAll(['id'=>$bannerId]);
                        if(!$bannerDel){
                            throw new \Exception('操作失败');
                        }
                    }
                }
            }else{
                $category = tools::arrayHasValue($data,'category') ? $data['category'] : [];
                $sku = tools::arrayHasValue($data,'sku') ? $data['sku'] : [];
                $sku_go = tools::arrayHasValue($data,'sku_go') ? $data['sku_go'] : [];
                $banner_config_id_category = tools::arrayHasValue($data,'banner_config_id_category') ? $data['banner_config_id_category'] : [];
                $banner_config_id_sku = tools::arrayHasValue($data,'banner_config_id_sku') ? $data['banner_config_id_sku'] : [];
                $banner_config_id_go = tools::arrayHasValue($data,'banner_config_id_go') ? $data['banner_config_id_go'] : [];
                //处理sku
                $sort = 1;
                if (count($banner_config_id_sku) > 0)for ($i=0;$i<count($banner_config_id_sku);$i++){
                    if ($sku[$i] == '') continue;
                    $find_sku = GoodsSaleEdit::find()->where(['sku'=>$sku[$i]])->asArray()->count();
                    if ($find_sku <= 0){
                        throw new \Exception('物料号'.$sku[$i].'，请确认物料号是否正确');
                    }
                    $banner = new BannerConfig();
                    if ($banner_config_id_sku[$i]){
                        $banner = $banner->findOne($banner_config_id_sku[$i]);
                        $banner->editor = $creator;
                        $banner->edit_time = $oper_time;
                    }else{
                        $banner->creator = $creator;
                        $banner->create_time = $oper_time;
                        $banner->type = 1;
                    }
                    $banner->group_id = $hot_sale_id;
                    $banner->group_name = $hot_sale_name;
                    $banner->sku = $sku[$i];
                    $banner->sort = $sort;
                    $banner->save();
                    $banner_id = $banner->attributes['id'];
                    if (!$banner_id){
                        throw new \Exception('热销商品明细操作失败');
                    }
                    $sort++;
                }
                if (is_array($banner_ids_sku) && count($banner_ids_sku))foreach ($banner_ids_sku as $banner_id_sku){
                    if (!in_array($banner_id_sku,$banner_config_id_sku)){
                        $bannerDel = BannerConfig::deleteAll(['id'=>$banner_id_sku]);
                        if(!$bannerDel){
                            throw new \Exception('操作失败');
                        }
                    }
                }
                //处理分类
                $sort = 1;
                if (count($banner_config_id_category) > 0)for ($i=0;$i<count($banner_config_id_category);$i++){
                    if ($category[$i] == '') continue;
                    $banner = new BannerConfig();
                    if ($banner_config_id_category[$i]){
                        $banner = $banner->findOne($banner_config_id_category[$i]);
                        $banner->editor = $creator;
                        $banner->edit_time = $oper_time;
                    }else{
                        $banner->creator = $creator;
                        $banner->create_time = $oper_time;
                    }
                    $banner->group_id = $hot_sale_id;
                    $banner->group_name = $hot_sale_name;
                    $banner->category_id = $category[$i];
                    $banner->sort = $sort;
                    $banner->save();
                    $banner_id = $banner->attributes['id'];
                    if (!$banner_id){
                        throw new \Exception('热销商品明细操作失败');
                    }
                    $sort++;
                }
                if (is_array($banner_ids_category) && count($banner_ids_category))foreach ($banner_ids_category as $banner_id_category){
                    if (!in_array($banner_id_category,$banner_config_id_category)){
                        $bannerDel = BannerConfig::deleteAll(['id'=>$banner_id_category]);
                        if(!$bannerDel){
                            throw new \Exception('操作失败');
                        }
                    }
                }
                //处理首页限时抢go sku
                $sort = 1;
                if (count($banner_config_id_go) > 0)for ($i=0;$i<count($banner_config_id_go);$i++){
                    if ($sku_go[$i] == '') continue;
                    $find_sku = GoodsSaleEdit::find()->where(['sku'=>$sku_go[$i]])->asArray()->count();
                    if ($find_sku <= 0){
                        throw new \Exception('物料号'.$sku_go[$i].'，请确认物料号是否正确');
                    }
                    $banner = new BannerConfig();
                    if ($banner_config_id_go[$i]){
                        $banner = $banner->findOne($banner_config_id_go[$i]);
                        $banner->editor = $creator;
                        $banner->edit_time = $oper_time;
                    }else{
                        $banner->creator = $creator;
                        $banner->create_time = $oper_time;
                        $banner->type = 2;
                    }
                    $banner->group_id = $hot_sale_id;
                    $banner->group_name = $hot_sale_name;
                    $banner->sku = $sku_go[$i];
                    $banner->sort = $sort;
                    $banner->save();
                    $banner_id = $banner->attributes['id'];
                    if (!$banner_id){
                        throw new \Exception('热销商品明细操作失败');
                    }
                    $sort++;
                }
                if (is_array($banner_ids_go) && count($banner_ids_go))foreach ($banner_ids_go as $banner_id_go){
                    if (!in_array($banner_id_go,$banner_config_id_go)){
                        $bannerDel = BannerConfig::deleteAll(['id'=>$banner_id_go]);
                        if(!$bannerDel){
                            throw new \Exception('操作失败');
                        }
                    }
                }
				//add by lizenan 20180410 修改功能：【后台需求】热卖商品改版限时抢GO商品，调整后台热卖商品功能 573 end
            }
            $transaction->commit();
            $this->retJson('编辑成功',200);
        }catch (\Exception $e){
            $transaction->rollBack();
            //add by allen.qiang 20180112 异常处理，日志优化 start
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //add by allen.qiang 20180112 异常处理，日志优化 end
            $this->retJson($e->getMessage(),500);
        }
    }
    
    public function actionSelectSaleSku(){
        $data = Yii::$app->request->post();
        $sku = $data['sku'];
        $sale_edit = GoodsSale::find()->select('sku')->where('use_flg=1');
        if ($sku) {
            $sale_edit = $sale_edit->andWhere(['like','sku',$sku]);
        }
        $sale_edit = $sale_edit->asArray()->all();
        $this->retJson($sale_edit,200);
    }
    //add by lizenan 20180410 修改功能：【后台需求】热卖商品改版限时抢GO商品，调整后台热卖商品功能 573 start
    public function actionExcelFileUpload(){
        try {
            if (count ( $_FILES ) == 0) {
                throw new \Exception('未上传文件');
            }
            $fileElementName = array_keys ( $_FILES );
            $fileElementName = $fileElementName [0];
            
            if (! $_FILES [$fileElementName]){
                throw new \Exception('未上传文件');
            }
            $file = $_FILES [$fileElementName];
            if($_FILES[$fileElementName]['size'] > 2097152) {//文件不能超过2M
                throw new \Exception('文件大小超过2M');
            }
            // 验证文件类型
            $lastdot = strrpos ( $file ['name'], "." ); // 找到区分文件名与扩展名的标记符“.”最后出现的位置
            $reader_type = substr ( $file ['name'], $lastdot + 1 ); // 取出扩展名
            $allowType = array ('xls','xlsx');
            if (! in_array ( strtolower ( $reader_type ), $allowType )) {
                throw new \Exception('只支持xls,xlsx文件');
            }
            $extend = ($reader_type == 'xlsx' ? 'Excel2007' : 'Excel5');
            set_time_limit(0);
            $excel = new PHPExcel();
            $cacheMethod = \PHPExcel_CachedObjectStorageFactory::cache_in_memory_serialized;
            $cacheSettings = array();
            \PHPExcel_Settings::setCacheStorageMethod($cacheMethod,$cacheSettings);
            $objReader = \PHPExcel_IOFactory::createReader($extend);
            $objPHPExcel = $objReader->load($file ['tmp_name']);
            $objWorksheet = $objPHPExcel->getActiveSheet();
            $highestRow = $objWorksheet->getHighestRow();
            if($highestRow < 2){
                throw new \Exception('上传文件数据不能为空');
            }
            if($highestRow > 1001){
                throw new \Exception('上传文件数据超过行数限制,最大不能超过一千条');
            }
            
            $highestColumn = $objWorksheet->getHighestColumn();// 取得总列数
            $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString ( $highestColumn ); // 总列数
            $dataKey = array();
            //商品导入标题对应键
            $excelTitle = array('sku'=>'SKU（物料号）');
            $dataKey = array_keys($excelTitle);
            $title = array_values($excelTitle);
            //获取数据集合
            $excelDataBefore = $excelData = $fileTitle = $data_arr =  array();
            for ($r = 1; $r <= $highestRow ;$r++){
                for($c = 0; $c < $highestColumnIndex; $c ++) {
                    $getCellByColumnAndRowResult = trim ( $objWorksheet->getCellByColumnAndRow ( $c, $r )->getValue () );
                    if($r == 1){
                        $fileTitle [] = $getCellByColumnAndRowResult;
                    }else if(array_key_exists($c, $dataKey)){
                        $excelDataBefore[][$dataKey[$c]] = $excelData[][$dataKey[$c]] =  $getCellByColumnAndRowResult;
                    }
                }
            }
            if(count($excelData) == 0) throw new \Exception('未解析到可用数据');
            $fieldsTitle=array();
            $i = 2;
            foreach ($title as $k =>$v){
                if($v !== $fileTitle[$k]){
                    throw new \Exception('上传文件标题('.$fileTitle[$k].')格式不正确,应为'.$v);
                }
            }
            return $this->retJson($excelData,200);
        } catch (\Exception $e) {
            //add by allen.qiang 20180112 异常处理，日志优化 start
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //add by allen.qiang 20180112 异常处理，日志优化 end
            return $this->retJson($e->getMessage(),500);
        }
    }
	//add by lizenan 20180410 修改功能：【后台需求】热卖商品改版限时抢GO商品，调整后台热卖商品功能 573 end
}